﻿
using Common;
using NB.MGJ.Common;
using NB.MGJ.Common.Helper;
using NB.MGJ.Common.MVC;
using NB.MGJ.Model;
using NB.MGJ.Service;
using NB.MGJ.Service.Market;
using NB.MGJ.Service.Config;
using NB.MGJ.Web.Controllers;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Senparc.Weixin.MP.AdvancedAPIs.OAuth;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebAppModel;
using WxPayAPI;
using System.Text.RegularExpressions;
 

namespace NB.MGJ.WebWap.Controllers.Marketing
{
    /// <summary>
    /// 活动模板  
    /// 2017年7月25日17:00:27
    /// Dy
    /// </summary>
    public class WebTemplateController : Controller
    {
        WXController _wx = new WXController();

        #region 视图
     
        public ActionResult dzpTemplate()
        {
            return View();
        }

        #endregion

        //MarketController marPC = new MarketController();
        MarketService _MarketService = new MarketService();
        ManagerService _manger = new ManagerService();
        TheWinningService _the = new TheWinningService();
        DBHService _dbhService = new DBHService();
        ConfigManagerService _config = new ConfigManagerService();

        #region 根据活动编号 中奖项
        /// <summary>
        /// 根据活动编号 中奖项
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAwards( )
        {
            try
            {
                UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
                string JiamiCode = user.JiemiCode;
                int Aid = user.Aid;
                List<Marketing_Awards> list = _MarketService.GetAwards_Aid(Aid);
                //中奖奖项
                Marketing_Awards awardModle = GetRandomAwards(list);
                //Hashtable ht = new Hashtable();
                //ht.Add("Denomination", awardModle.Denomination);
                //ht.Add("EnterpriseName", awardModle.EnterpriseName);
                //ht.Add("Congrats", awardModle.Congrats);
                //ht.Add("ButtonId", EDS3.DESEnCode(awardModle.ButtonId.ToString()));
                //ht.Add("AID", EDS3.DESEnCode(awardModle.ActivityId.ToString()));
                /// 类型 1: 红包 2: 优惠券 3:  流量包 根据奖池一样
                //ht.Add("Type",awardModle.type);

                string tableName = "Marketing_TheWinning" + user.eCode;
             
                user.AwId= awardModle.Id ;
                user.Denomination = awardModle.Denomination;
                Session["user"] = user;
               
                //把中奖数据记录下来
                Marketing_TheWinning wmodel = _the.GetTheWinningModel(user.eCode,user.JiemiCode);
                wmodel.Denomination = awardModle.Denomination;
                wmodel.Address = (Session["user"] as UserScanQRInfoModel).address;
                wmodel.State =EnumManagement.GetEnumValue( EnumTheWinningState.NotGetDraw);
                wmodel.AwardsID = awardModle.Id;
                _the.UpdateTheWinning(wmodel, user.eCode);
                Marketing_Activity ActivityModel= _MarketService.GetActivityModel(Aid);
                awardModle.Sponsor = _MarketService.GetActivityInfo((int)ActivityModel.ActivityInfoID).Sponsor;
                return Json(awardModle, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("GetAwardsErr", ex.ToString());
                throw;
            }
        }



        #endregion


        #region 领取奖品
        JsApiPay jsApiPay = new JsApiPay();




        /// <summary>
        /// 发给客户奖品 领取奖品
        /// </summary>
        /// <param name="AwardID">奖项ID</param>
        /// <param name="code">编号</param>
        /// <param name="Phone">电话号码</param>
        /// <param name="name">姓名</param>
        /// <returns>entity.mag 操作成功和失败    </returns>
        public int ToReceive(string Phone)
        {
            try
            {
                UserScanQRInfoModel sacn = Session["user"] as UserScanQRInfoModel;
                decimal Denomination = sacn.Denomination;
                string AwardID = sacn.AwId.ToString();

                int result = 0;
                //获取奖品实体
                Marketing_Awards model = _MarketService.GetAwardsModel(sacn.AwId);
                Marketing_Jackpot jmodel = _MarketService.GetJackpotModel((int)model.JackpotID);

                if (model.type ==EnumManagement.GetEnumValue(  AwardTypeEnum.LLB))//领取流量
                {
                    var obj = DataApi.GetPhoneInfo(Phone);
                    //判断手机号码的运营商  在给用户发对应的流量
                    string JsonResult = ((JObject)JsonConvert.DeserializeObject(DataApi.GetPhoneInfo(Phone)))["result"].ToString();

                    string company = ((JObject)JsonConvert.DeserializeObject(JsonResult))["company"].ToString();  //序列化（也可使用JToken代替JObject）  
                    //string company= obj["company"].ToString();
                    //根据用户手机号类型返回供应商
                    int DataID = Convert.ToInt32(company == "联通" ? jmodel.DataID1_LT : company == "移动" ? jmodel.DataID2_YD : jmodel.DataID3_DX);
                    //根据流量ID  获取流量的金额  通过接口获取数据
                    // string jsonData = ((JObject)JsonConvert.DeserializeObject(DataApi.getFlowTable_toStr()))["result"].ToString().Substring(1).TrimEnd(']');
                    JObject jsonData = ((JObject)JsonConvert.DeserializeObject(DataApi.getFlowTable_toStr()));
                    foreach (var item in jsonData["result"][0]["flows"])
                    {
                        flows f = JsonHelper.JsonToObject<flows>(item.ToString());
                        if (f.id == DataID.ToString())
                        {
                            Denomination = f.inprice;
                            break;
                        }
                    }
                    //调用流量领取接口 
                    DataApi.SendData(Phone, DataID, "NB" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));

                }
                else if (model.type ==EnumManagement.GetEnumValue(AwardTypeEnum.HB))//领取红包 红包不要减去金额  是从客户微信商户号里发红包
                {
                    WXPortController _WxPay = new WXPortController();
                    config_WX wxConfigMolde = Session["wxConfig"] as config_WX;
                    //SendRedPacket(sacn.OpenID, Denomination);公众号发放
                    //发放金额
                    _WxPay.EnterprisePayUser(sacn.OpenID, Denomination, wxConfigMolde);
                }
                //减去发放流量的数量  以及金额
                result = ToReceiveBll(model, sacn.JiemiCode, sacn.Uid, Phone, sacn.WXName, Denomination);
                //插入中奖纪录数据

                //减去数据库的数据
                return result;
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("发给客户奖品err", ex.ToString());
                throw;
            }
        }

        /// <summary>
        /// 领取奖品 减去数据
        /// </summary>
        /// <param name="Awards"></param>
        /// <returns></returns>
        public int ToReceiveBll(Marketing_Awards model, string code, int Uid, string Phone, string Name, decimal Denomination)
        {
            try
            {
 
                Marketing_Jackpot j = _MarketService.GetJackpotModel(int.Parse(model.JackpotID.ToString()));
                model.ResidueMoney = model.ResidueMoney - Denomination;
                model.ResidueNums = model.ResidueNums - 1;
                UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
                //减去奖项的数据
                _MarketService.UpdateAwards(model);
                //中奖纪录ID
                int tid = (_the.GetTheWinningModel(user.eCode, code) as Marketing_TheWinning).Id;
                //需改用户电话号码
                _the.FillPhone(user.eCode, Phone, tid, (Session["user"] as UserScanQRInfoModel).Uid);
                _the.UpdateTheWinningState(tid,EnumManagement.GetEnumValue( EnumTheWinningState.GetAwardSucceed) ,user.eCode);     //修改状态  
                return tid;
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("领取奖品减去数据err", ex.ToString());
                throw;
            }
        }


        #endregion


        //#region 分页 默认显示20 金额最高排序
        ///// <summary>
        ///// 分页 默认显示20 中奖时间排序
        ///// </summary>
        ///// <param name="pageIndex">开始页 1</param>
        ///// <param name="pageSize">显示页 20</param>
        ///// <param name="sortField">排序字段 </param>
        ///// <param name="sortOrder">排序类型</param>
        ///// <param name="key">条件</param>
        ///// <returns></returns>
        //public ActionResult GetTheWinning(int pageIndex, int pageSize, string sortField, string sortOrder, string key)
        //{
        //    pageIndex++;
        //    PagerModel pm = new PagerModel();
        //    pm.Page = pageIndex;
        //    pm.PageSize = pageSize;
        //    pm.FldSort = sortField + " " + sortOrder;
        //    pm.TblName = "Marketing_TheWinning" + (Session["user"] as UserScanQRInfoModel).Code.Substring(0,4);
        //    TheWinningBLL wbll = new TheWinningBLL();
        //    List<TheWinningModel> list = wbll.GetPagerList(ref pm);
        //    return Json(list, JsonRequestBehavior.AllowGet);
        //}
        //#endregion

        #region 发送手机验证码  聚合数据接口
        /// <summary>
        /// 发送短信
        /// </summary>
        /// <returns></returns>
        public string SMSApi(string phoneNum )
        {
            try
            {
                 
                config_SMS smsModel = _config.GetSMSApiModel((Session["user"] as UserScanQRInfoModel).Eid);
                SMSApi sms = new SMSApi();
                string WXName = (Session["user"] as UserScanQRInfoModel).WXName;
                WXName= Regex.Replace(WXName, @"\p{Cs}", "");
                string reulst = sms.SendSMSApi(smsModel.Appkey, phoneNum, smsModel.ModelCode,WXName);
                //  string reulst = sms.SendSMSApi(appkey, phoneNum, tpl_id,"她、");
                return reulst;
            }
            catch (Exception ex)
            {
                WeiXinHelper.WriteLog("SMSApi错误", ex.ToString());
                throw;
            }
        }
        #endregion

        #region  判断手机号码供应商

        /// <summary>
        /// 获取手机号归属地
        /// </summary>
        /// <param name="phone"></param>
        /// <returns></returns>
        public JsonResult GetPhoneSupplier(string phone)
        {
            return Json(DataApi.GetPhoneInfo(phone), JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 根据码 获取活动实体
        public Marketing_Activity GetActivityCode(string code)
        {
            UserScanQRInfoModel user = Session["user"] as UserScanQRInfoModel;
            string eid = user.eCode;
            string bid = user.BatchId;

            Organization_Enterprise model = _manger.GetInfoByCodeModel(eid);
            Marketing_Activity act = _MarketService.GetActivity(model.ID, int.Parse(bid.TrimStart('0')));
            return act;
        }
        #endregion

        #region  查询该码是否被查询过
        /// <summary>
        /// 查询该码是否被查询过 查询过返回查询的数据
        /// </summary>
        /// <param name="code">码的前4位</param>
        /// <returns></returns>
        //public Marketing_TheWinning IsTheWinningData(string code)
        //{
        //    bool reulst = true;
        //    string eid = code.Substring(0, 4);
        //    string tableName = "Marketing_TheWinning" + eid;
        //    if (dbh.TabExists(tableName))
        //    {
        //       Marketing_TheWinning theWinning=  _MarketService.IsTheWinningData(tableName, code);
        //       if (theWinning==null)
        //       {
        //            theWinning.ButtonId=0;
        //       } 
        //        return theWinning;
        //    }
        //    return null;
        //}
        #endregion

        /// <summary>
        /// 中奖率控制
        /// 2017年7月27日14:45:02
        /// Dy
        /// </summary>
        ///  <param name="list">Sequence排序好的奖项list</param>
        /// <returns></returns>
        public Marketing_Awards GetRandomAwards(List<Marketing_Awards> list)
        {
            var rand = new Random();
            int i = rand.Next(0,10000);
            double index = 0;
            double end = 0;
            Dictionary<double, double> rate = new Dictionary<double, double>();
            foreach (var item in list)
            {
                end += double.Parse(item.Rate.ToString()) * 100;
                rate.Add(index, end);
                if (i >= index && i <= end)
                {
                    //判断奖池有没有奖品 
                    if (item.ResidueNums <= 0)
                    {
                        i = rand.Next(0, 10000);
                         index = 0;
                         end = 0;
                        continue;
                    }
                    //查询中奖的奖项
                    Marketing_Jackpot j = _MarketService.GetJackpotModel(int.Parse(item.JackpotID.ToString()));

                    //手气红包
                    if (j.Type == 1 && j.CouponType == 0)
                    {
                        item.Denomination = GetLuckRadPacket(j, item);
                    }

                    item.ResidueMoney = item.ResidueMoney - item.Denomination;
                    item.type = j.Type;
                    return item;
                }
                index = end;
            }
            Marketing_Awards a = new Marketing_Awards();
            a.ActivityId = list[0].ActivityId;
            a.Id = 0;
            a.Congrats = "没有中到奖品！";
            a.EnterpriseName = list[0].EnterpriseName;
            a.AwardsGrade = -1;
            a.Denomination = -1;
            return a;
        }


        /// <summary>
        /// 运气红包
        /// 2017年7月27日14:45:02
        /// Dy
        /// </summary>
        /// <returns></returns>
        public decimal GetLuckRadPacket(Marketing_Jackpot jackpot, Marketing_Awards awards)
        {
            Random rand = new Random();
            int min = Convert.ToInt32(jackpot.MinDenomination * 100);
            decimal maxTimes = Convert.ToDouble(jackpot.TotalMoney / awards.TotalNums * 2) > Convert.ToDouble(jackpot.MaxDenomination) ? jackpot.MaxDenomination : Convert.ToDecimal(jackpot.TotalMoney / jackpot.TotalNums * 2);
            int max = Convert.ToInt32(maxTimes * 100);
            decimal money = rand.Next(min, max);
            return money / 100;
        }



        #region 中奖明细
        /// <summary>
        ///中奖明细
        /// </summary>
        /// <param name="pageIndex">起始页</param>
        /// <param name="pageSize">显示行数</param>
        /// <param name="sortField">排序字段</param>
        /// <param name="asearch">查询条件</param>
        /// <param name="search">详细查询条件</param>
        /// <param name="aid">活动id</param>
        /// <param name="awardsId">奖项id</param>
        /// <param name="jId">奖池id</param>
        /// <param name="uId">用户id</param>
        /// <returns></returns>
        public JsonResult GetTheWinningList(string sortField, string sortOrder, string asearch, int pageIndex = 1, int pageSize = 10, int aId = 0, int awardsId = 0, int jId = 0, int uId = 0)
        {
   
            //aId= (Session["user"] as UserScanQRInfoModel).Aid;
            PagerModel pm = new PagerModel();
            string where = " state="+EnumManagement.GetEnumValue( EnumTheWinningState.GetAwardSucceed);
            if (aId != 0)
            {
                where += " and t.ActivityID=" + aId;
            }
            if (awardsId != 0)
            {
                where += " and t.AwardsID=" + awardsId;
            }
            if (jId != 0)
            {
                where += " and j.id=" + jId;
            }
            if (uId != 0)
            {
                where += " and u.id=" + uId;
            }
            pm.StrCondition = where;
            pm.Page = pageIndex;
            pm.PageSize = pageSize;
            pm.FldSort = sortField;
            MarketService _mserice = new MarketService();
             
            //string eCode="0001";
            var roleList = _mserice.GetTheWinningList(ref pm, (Session["user"] as UserScanQRInfoModel).eCode);
            return Json(roleList, JsonRequestBehavior.AllowGet);

           
        }

        #endregion

   

    }
}
